<?php
class User_Model_TypeMapper {
	protected $_dbTable;

	public function __construct() {

	}

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('User_Model_DbTable_Type');
		}
		return $this->_dbTable;
	}



	public function populateTypeFromArray($array, User_Model_Type $typeModel) {
		$typeModel->_tid = $array['tid'];
		$typeModel->_typename = $array['typename'];
		$typeModel->_description = $array['description'];

	}

	public function populateTypeFromRow(Zend_Db_Table_Row_Abstract $row, User_Model_Type $typeModel) {
		$typeModel->_tid = $row->tid;
		$typeModel->_typename = $row->typename;
		$typeModel->_description = $row->description;
	}


	public function save(User_Model_Type $typeInfo)
	{
		$tid = $typeInfo->_tid;
		$data = array(
			'tid' => $typeInfo->_tid,
            'typename'   => $typeInfo->_typename,
            'description' => $typeInfo->_description,
		);

		if (!isset($tid)) {
			unset($data['tid']);
			return $this->getDbTable()->insert($data);
		} else {
			return $this->getDbTable()->update($data, array('tid = ?' => $tid));
		}
	}

	public function find($tid, User_Model_Type $typeInfo)
	{
		$result = $this->getDbTable()->find($tid);
		if (0 == count($result)) {
			return false;
		}
		$row = $result->current();
		$this->populateTypeFromRow($row, $typeInfo);
		return true;
	}

	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new User_Model_Type();
			$this->populatetypeFromRow($row, $entry);
			$entries[] = $entry;
		}
		return $entries;
	}

}